package org.cli.admin.cli.printer;

import static org.fusesource.jansi.Ansi.ansi;
import static org.fusesource.jansi.Ansi.Color.GREEN;

import java.io.IOException;

import jline.ConsoleReader;

import org.cli.admin.cli.printer.ui.SelectItem;
import org.cli.admin.cli.printer.ui.SelectItems;
import org.fusesource.jansi.Ansi;
import org.fusesource.jansi.Ansi.Color;

import com.beust.jcommander.JCommander;
import com.google.inject.Inject;

public class ConsolePrinter {

	@Inject
	private ConsoleReader reader;

	@Inject
	private JCommander jCommander;

	public void printGreeting() {
		System.out.println(ansi().eraseScreen().a(Ansi.Attribute.INTENSITY_BOLD).fg(GREEN).a("Welcome to ").fg(Ansi.Color.RED).a("Admin-CLI").fg(GREEN)
				.a(" application!").newline().reset());
		jCommander.usage();
	}

	public void printEnterCommand() {
		System.out.println(ansi().a(Ansi.Attribute.INTENSITY_BOLD).fg(Ansi.Color.GREEN).a("Enter the command:").reset());
	}

	public <T> SelectItem<T> printSelectedList(SelectItems<T> items) {
		System.out.println(ansi().a(Ansi.Attribute.INTENSITY_BOLD).a(items.getQuestionText()).reset());

		int i = 0;
		for (SelectItem<T> item : items.getItems()) {
			System.out.println(ansi().a(Ansi.Attribute.INTENSITY_BOLD).a(i).a(".").reset().a(Ansi.Attribute.ITALIC).a(" ").a(item.getMessage()).reset());

			i++;
		}

		boolean selectDone = false;
		synchronized (reader) {

			while (!selectDone) {
				try {
					System.out.print(ansi().a(Ansi.Attribute.INTENSITY_BOLD).a("Choose:"));
					if (items.getSelectedItem() != null) {
						int id = items.getItems().indexOf(items.getSelectedItem());
						if (id != -1) {
							System.out.print(ansi().a(" [").a(id).a("]").newline().reset());
						}
					}

					String input = reader.readLine();

					if ((input == null || input.isEmpty()) && items.getSelectedItem() != null) {
						return items.getSelectedItem();
					}

					int selectedId = Integer.parseInt(input);

					SelectItem<T> selected = items.getItems().get(selectedId);

					return selected;
				} catch (IOException e) {
					return items.getSelectedItem();
				} catch (NumberFormatException ex) {
					System.out.println(ansi().a(Ansi.Attribute.INTENSITY_BOLD).fg(Color.RED).a("Not an integer!!!Please try again.").newline().reset());
				} catch (IndexOutOfBoundsException e) {
					System.out.println(ansi().a(Ansi.Attribute.INTENSITY_BOLD).fg(Color.RED).a("Not in specified range!!!Please try again.").newline().reset());
				}
			}
		}
		return items.getSelectedItem();
	}
}
